package com.feng.sprider;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

public class Down {

	HttpClient client = HttpClients.createDefault();
	HttpResponse response;

	public void downImg(String url) {
		HttpGet get = new HttpGet(url);

		try {
			// 运行时卡在这里
			// 空的运行第三次就死

			// 设置连接超时
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(2000).setConnectionRequestTimeout(2000)
					.build();// 请求时间 传输时间

			get.setConfig(requestConfig);
			// 结束

			response = client.execute(get);

			// client.getConnectionManager().getSchemeRegistry().

			HttpEntity entity = response.getEntity();

			InputStream is = entity.getContent();

			File fileName = new File("Image/");
			if (!fileName.exists()) {
				fileName.mkdirs();
			}// 没有就新建

			// http://image.nationalgeographic.com.cn/2015/0625/20150625055336953.jpg
			
			String imgFormat = url.substring(url.lastIndexOf("."));
//			System.out.println(imgFormat);
			
			File file = new File("Image/"
					+ url.substring(url.lastIndexOf("/"), url.lastIndexOf("."))
					+ imgFormat);

			FileOutputStream fos = new FileOutputStream(file);

			byte b[] = new byte[1024];
			int l = 0;
			while ((l = is.read(b)) != -1) {
				fos.write(b, 0, l);
			}
			
			fos.flush();
			fos.close();
			// isr.close();
			is.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}
	}

}
